package com.gzw.dms.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.gzw.dms.KJ.SelectCityActivity;

import com.gzw.dms.KJ.SelectJySuppliesActivity;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.base.BaseSpinnerAdapter;
import com.gzw.dms.bean.AddressInfo;
import com.gzw.dms.bean.DriverInfo;
import com.gzw.dms.bean.SpinnerInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class DriverActivity extends BaseActivity {
    private Button btn_sign;
    private Context mContext;
    private Toolbar toolbar;
    private TextView ic_username, ic_phone1, ic_idnumber1,ic_adress,ic_gongyingshang;
    private EditText ic_username2, ic_phone2, ic_idnumber2, tv_carnumber,
            tv_phonetype, tv_phonesate, tv_remark;
    private Spinner sp_identity;
    private String  type = "0";
    private DriverInfo info;
    private ProgressDialog mProgressDialog;
    private String adress,driver_province,driver_city,driver_county,gys_id,fpstste;
    private AddressInfo addressInfo;
    private Intent mIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_driver);

    }

    @Override
    protected void initViews() {

        btn_sign = (Button) findViewById(R.id.btn_sign);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ic_username = (TextView) findViewById(R.id.ic_username).findViewById(R.id.tv_left);
        ic_phone1 = (TextView) findViewById(R.id.ic_phone).findViewById(R.id.tv_left);
        ic_idnumber1 = (TextView) findViewById(R.id.ic_idnumber).findViewById(R.id.tv_left);
        sp_identity = ((Spinner) findViewById(R.id.sp_identity));
        ic_username2 = (EditText) findViewById(R.id.ic_username).findViewById(R.id.et_right);
        ic_phone2 = (EditText) findViewById(R.id.ic_phone).findViewById(R.id.et_right);
        ic_idnumber2 = (EditText) findViewById(R.id.ic_idnumber).findViewById(R.id.et_right);
        tv_carnumber = (EditText) findViewById(R.id.tv_carnumber);
        tv_phonetype = (EditText) findViewById(R.id.tv_phonetype);
        tv_phonesate = (EditText) findViewById(R.id.tv_phonesate);
        tv_remark = (EditText) findViewById(R.id.tv_remark);
        ic_adress = (TextView) findViewById(R.id.ic_adress);
        ic_gongyingshang = (TextView) findViewById(R.id.tv_gongyingshang);


    }

    @Override
    protected void initData() {
        mContext = this;
        mIntent = getIntent();

        ArrayList ls = new ArrayList();
        ls.add(new SpinnerInfo("1", "面包车"));
        ls.add(new SpinnerInfo("2", "金杯车"));
        ls.add(new SpinnerInfo("3", "依维柯"));
        ls.add(new SpinnerInfo("4", "4.2箱车"));
        ls.add(new SpinnerInfo("5", "三轮车"));
        ls.add(new SpinnerInfo("6", "3.5箱车"));

        BaseSpinnerAdapter Adapter = new BaseSpinnerAdapter(mContext, ls);
        sp_identity.setAdapter(Adapter);
        ic_username.setText("姓        名:");
        ic_phone1.setText("联系方式:");
        ic_idnumber1.setText("身份证号:");
        addressInfo=new AddressInfo();
        fpstste = (String)mIntent.getExtras().get("fpstste");
        if (fpstste.equals("0")){
            toolbar.setTitle("添加司机");
        }else {
            toolbar.setTitle("修改司机");

        }
        if (fpstste.equals("1")){
            info = (DriverInfo) mIntent.getExtras().get(
                    "driverInfo");
             setData(info);
        }

    }

    @Override
    protected void initEvents() {

        btn_sign.setOnClickListener(new myOnClick());
        ic_gongyingshang.setOnClickListener(new myOnClick());
        ic_adress.setOnClickListener(new myOnClick());

        toolbar.setNavigationOnClickListener(new myOnClick());

        sp_identity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
    }


    public void SaveHttpClientPost() {
        if (isNull(ic_username2)) {
            T.showShort(mContext, "姓名不能为空");
            return;
        }

        if (isNull(ic_phone2)) {
            T.showShort(mContext, "联系方式不能为空");
            return;
        }
        if (isNull(ic_idnumber2)) {
            T.showShort(mContext, "身份证号不能为空");
            return;
        }
        if (isNull(ic_adress)) {
            T.showShort(mContext, "终到位置不能为空");
            return;
        }


            SpinnerInfo spinnerInfo = (SpinnerInfo) sp_identity.getSelectedItem();
            type = spinnerInfo.getText();

            if (info == null)
                info = new DriverInfo();
            info.setDriver_name(ic_username2.getText().toString().trim());
            info.setDriver_phone(ic_phone2.getText().toString().trim());
            info.setDriver_cardnumber(ic_idnumber2.getText().toString().trim());
            info.setDriver_carnumber(tv_carnumber.getText().toString().trim());
            info.setDriver_phonebrand(tv_phonetype.getText().toString().trim());
            info.setDriver_address(ic_adress.getText().toString().trim());
            info.setDriver_phonemodel(tv_phonesate.getText().toString().trim());
            info.setDriver_remarks(tv_remark.getText().toString().trim());
            info.setDriver_cartype(type);
            info.setDriver_countyname(driver_county);
            info.setDriver_city(Integer.parseInt(driver_city));
            info.setDriver_province(Integer.parseInt(driver_province));
            info.setDriver_suppliers(gys_id);
        if (fpstste.equals("1")){
            Change change = new Change();
            change.execute(info);
        }else {
            SignShipOrder signShipOrder = new SignShipOrder();
            signShipOrder.execute(info);
        }
    }

    public class SignShipOrder extends AsyncTask<DriverInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);

        }

        protected String doInBackground(DriverInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userName", userInfo.getUsername());
            map.put("driverInfo", params[0]);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appAddDriverInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }
    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sign:
                    SaveHttpClientPost();
                    break;
                case R.id.ic_adress:
                    Intent mIntent1 = new Intent();
                    mIntent1.putExtra("who", "0");
                    mIntent1.setClass(mContext, SelectCityActivity.class);
                    startActivityForResult(mIntent1, 2);
                    break;

                case R.id.tv_gongyingshang:
                    Intent mIntent21 = new Intent();
                    mIntent21.putExtra("type", "0");
                    mIntent21.setClass(mContext, SelectJySuppliesActivity.class);
                    startActivityForResult(mIntent21, 4);
                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 0){
            try {

//                ArrayList<String> name1 = data.getStringArrayListExtra("name");
//                String name2 = name1.toString();
//                String name = name2.substring(1,name2.length()-1);
                String name = data.getStringExtra("name");
                String id = data.getStringExtra("id");

            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 2){
            try {
                String province = data.getStringExtra("province");
                String city = data.getStringExtra("city");
                String county = data.getStringExtra("county");
                driver_province = data.getStringExtra("province_id");
                driver_city = data.getStringExtra("city_id");
                String county_id = data.getStringExtra("county_id");
                String str2 = county.substring(1, county.length()-1);
                String str = province+city+str2;
                adress=str;
                ic_adress.setText(str);
                driver_county = county_id.substring(1,county_id.length()-1);

            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 1){
            try {
                String name = data.getStringExtra("name");
                String id = data.getStringExtra("id");

            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 3){
            try {
                String name = data.getStringExtra("name");
                String id = data.getStringExtra("id");

            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 4){
            try {
                String name = data.getStringExtra("name");
                gys_id = data.getStringExtra("id");
                ic_gongyingshang.setText(name);

            } catch (Exception e) {
                // TODO: handle exception
            }
        }


    }
    private void setData(DriverInfo driverInfo) {
        ic_username2.setText(driverInfo.getDriver_name());
        ic_phone2.setText(driverInfo.getDriver_phone());
        ic_idnumber2.setText(driverInfo.getDriver_cardnumber());
        tv_carnumber.setText(driverInfo.getDriver_carnumber());
        ic_adress.setText(driverInfo.getDriver_address());
        ic_gongyingshang.setText(driverInfo.getDriver_suppliersname());
        tv_phonesate.setText(driverInfo.getDriver_phonemodel());
        tv_phonetype.setText(driverInfo.getDriver_phonebrand());
        tv_remark.setText(driverInfo.getDriver_remarks());
        btn_sign.setText("修       改");
//        driver_province,driver_city,driver_county,gys_id,
        driver_province = driverInfo.getDriver_province().toString();
        driver_city = driverInfo.getDriver_city().toString();
        driver_county = driverInfo.getDriver_countyname().toString();
        driver_province = driverInfo.getDriver_province().toString();
        gys_id = driverInfo.getDriver_suppliers();
        type=driverInfo.getDriver_cartype();
        SpinnerInfo spinnerInfo = (SpinnerInfo) sp_identity.getSelectedItem();
        spinnerInfo.setText(type);
    }


    public class Change extends AsyncTask<DriverInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(DriverInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userName", userInfo.getUsername());
            map.put("driverInfo", params[0]);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appUpdateDriverInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }

}
